package rwt.server.handlers;

import rwt.server.*;
import rwt.server.RailroadMessages.PutInitOutcomeMsg;
import rwt.server.WebMessages.PutInitializeTrain;
import rwt.server.core.*;
import rwt.server.railroad.Train;

public class PutInitOutcomeHandler extends MessageHandler<PutInitOutcomeMsg>
{
	private static class Errors
	{
		public static final int INVALID_SENSOR_NUMBERS = 121;
		public static final int INSUFFICIENT_SLOTS = 122;
		public static final int OTHER_INIT_IN_PROGRESS = 123;
		public static final int POSITION_CONFLICT = 124;
	}
	
	private static final int MAX_VALID_PHYSICAL_SLOT = 120;
	
	@Override
	public void handle(PutInitOutcomeMsg message, IConnection source) throws Exception
	{
		int trainId = message.physicalLocoAddress;
		Train train = RailServer.getTrainManager().getTrainById(trainId);
		
		if (message.physicalSlotNum <= MAX_VALID_PHYSICAL_SLOT)
		{
			train.setInitialized(message.physicalSlotNum, message.virtualLocoAddress, message.virtualSlotNum);
			if (train.getInitializingClient() != null)
				train.getInitializingClient().write(new PutInitializeTrain(trainId));
			RailServer.getClientManager().sendToAll(RailServer.getTrainManager().getPutAvailableTrains());
		}
		else
		{
			// Railroad reports initialization error
			String reason;
			if (message.physicalSlotNum == Errors.INVALID_SENSOR_NUMBERS)
				reason = "Invalid sensor numbers";
			else if (message.physicalSlotNum == Errors.INSUFFICIENT_SLOTS)
				reason = "Insufficient slots available";
			else if (message.physicalSlotNum == Errors.OTHER_INIT_IN_PROGRESS)
				reason = "Another initialization is in progress";
			else if (message.physicalSlotNum == Errors.POSITION_CONFLICT)
				reason = "Position conflicts with that of another train";
			else
				reason = "Unknown error! Code: " + message.physicalSlotNum;
			
			train.clearInitialized();
			RailServer.getClientManager().sendToAll(new PutInitializeTrain(trainId, reason));
		}
	}
}
